//
//  EMUser.m
//  EMMODaliy
//
//  Created by karry on 2020/4/25.
//  Copyright © 2020 miki. All rights reserved.
//

#import "USUser.h"
//#import "EMGuideViewController.h"
#import "SceneDelegate.h"
#import "USRealtimeLocationManager.h"
#import <WidgetKit/WidgetKit.h>
#import "us-Swift.h"

@implementation USCharacter



@end

@implementation USUser

MJCodingImplementation

+ (BOOL)supportsSecureCoding{
    return YES;
}

+ (NSString *)localFilePath{
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"local_user_data"];
}


+ (USUser *)user {
    NSString *filePath = [self localFilePath];
    NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];
    if (!data) return nil;

    return [NSKeyedUnarchiver unarchivedObjectOfClasses:[NSSet setWithObjects:[USUser class],[NSString class], nil]
                                             fromData:data
                                                error:nil];
}

+ (NSArray *)mj_ignoredCodingPropertyNames {
    return @[@"character", @"relCharacter"];
}

+ (NSArray *)mj_ignoredPropertyNames {
    return @[@"character", @"relCharacter"];
}

+ (BOOL)saveUser:(USUser *)user {
    
    NSString *filePath = [self localFilePath];
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:user
                                         requiringSecureCoding:NO
                                                         error:nil];
    if (!data) {
        return NO;
    }
    
    BOOL ret = [data writeToFile:filePath atomically:YES];
    
    [self syncUserDataToWidget:user];
    
    NSLog(@"保存用户成功");
    
    return ret;
    
}

//数据存到小组件
+ (void)syncUserDataToWidget:(USUser *)user {
    
    if (!user) return;
    
    NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.emmo.us"];
    
    [defaults setObject:user.nickname forKey:@"nickname1"];
    [defaults setObject:user.relUser.nickname forKey:@"nickname2"];
    [defaults setObject:@(user.metTime) forKey:@"startTime"];
    [defaults synchronize];
    
    // 保存头像图像到 App Group（如果你用的是图像）
    NSURL *containerURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.emmo.us"];
    if (containerURL) {
        // 保存自己头像
        UIImage *img1 = [user.character snapshotImage]; // 例如你生成的卡通图
        if (img1) {
            NSData *data = UIImagePNGRepresentation(img1);
            [data writeToURL:[containerURL URLByAppendingPathComponent:@"my.png"] atomically:YES];
        }
        // 保存对方头像
        UIImage *img2 = [user.relCharacter snapshotImage];
        if (img2) {
            NSData *data = UIImagePNGRepresentation(img2);
            [data writeToURL:[containerURL URLByAppendingPathComponent:@"rel.png"] atomically:YES];
        }
    }
    
    [WidgetHelper reloadWidget];
    
}


+ (void)cancelLogin{
    
    [self updateCancelStateToServer];
 

}


+ (void)cancelUser {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];

    [params setValue:USUser.user.userId forKey:@"myselfUserId"];
  
    [[EMNetWork shareManager]em_post:API_CancelUser params:params hud:@"" showError:YES success:^(EMApiModel *api) {
        if (api.success == NO) {
            return;
        }
        
        [self saveUser:nil];
        
        [[[EMClient sharedClient].chatManager getConversationWithConvId:USUser.user.relImUserName] deleteAllMessages:nil];//删除本地环信数据

        [[EMClient sharedClient] logout:YES];//退出环信

        UIWindowScene *scene = (UIWindowScene *)[UIApplication sharedApplication].connectedScenes.allObjects.firstObject;
        
        SceneDelegate *sceneDelegate = (SceneDelegate *)scene.delegate;
        
        [sceneDelegate switchToLoginInterface];

    } fail:^{
        
    }];
}

- (NSString *)sexDescription {
    switch (self.sex) {
        case 0:
            return @"女";
        case 1:
            return @"男";
        default:
            return @"未设置";
    }
}

- (NSString *)birthdayDescription {
    if (self.birthday.length > 0) {
        return [NSDateFormatter localizedStringFromDate:[NSDate dateWithTimeIntervalSince1970:[self.birthday integerValue]] dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];
    }
    return @"";

}
- (NSInteger)metTimeDescription {
    if (self.metTime == 0) {
        return 1;
    }
    NSCalendar *calendar = [NSCalendar currentCalendar];
  
    NSDate *anniversaryDate = [calendar startOfDayForDate:[NSDate dateWithTimeIntervalSince1970:self.metTime]]; // 当日凌晨 0 点

    NSInteger days = [[NSDate now] jk_daysAfterDate:anniversaryDate];
    return days + 1;
}
///通知后台你退出登录了
+ (void)updateCancelStateToServer{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];

    [params setValue:USUser.user.userId forKey:@"myselfUserId"];
  
    [self cleanUserInfo];

    [[EMNetWork shareManager]em_post:API_Logout params:params hud:@"" showError:YES success:^(EMApiModel *api) {
        if (api.success == NO) {
            return;
        }

    } fail:^{
        
    }];
    
}
///清楚账户信息并回到登录页
+ (void)cleanUserInfo {
    [self saveUser:nil];
    
    [[USRealtimeLocationManager shared]saveRelUserLocationInfo:nil];//清空关联用户位置信息
    
    [[EMClient sharedClient] logout:YES];//退出环信
    
    UIWindowScene *scene = (UIWindowScene *)[UIApplication sharedApplication].connectedScenes.allObjects.firstObject;
    
    SceneDelegate *sceneDelegate = (SceneDelegate *)scene.delegate;
    
    [sceneDelegate switchToLoginInterface];

}

+ (BOOL)isLogin{
    NSString *userId = [USUser user].userId;
    if (userId.length > 0) {
        return YES;
    }
    return NO;
}

+ (BOOL)checkLoginFrom:(UIViewController *)viewController{
    
    BOOL ret = [self isLogin];
    
    if (!ret) {

//        EMGuideViewController *loginVC = [[EMGuideViewController alloc]init];
//
//        MONavigationController *navc = [[MONavigationController alloc]initWithRootViewController:loginVC];
//        
//
//        navc.modalPresentationStyle = 0;
//        
//        viewController = viewController?viewController:[UIViewController topViewController];
//        
//        [viewController presentViewController:navc animated:YES completion:nil];
    }
    
    return ret;
    
}


+ (void)foucsAuthor:(NSString *)authorId
            isFocus:(BOOL)isFocus
              block:(void(^)(BOOL success))block{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"linkUserId"] = authorId;
    NSString *path = isFocus?@"user/addUserLink":@"user/removeUserLink";
    
    [[EMNetWork shareManager]em_post:path params:params hud:@"" showError:YES success:^(EMApiModel *api) {
        !block?:block(api.success);
        } fail:^{
            !block?:block(NO);
    }];
    
}


- (void)clearCharacter{
    _character = nil;
    _relCharacter = nil;
}

//卡通形象
- (USCartoonCharacter *)character{
    if (!_character) {
        _character = [self userCharacter:USCartoonCharacterType_My];
    }
    return _character;
}

- (USCartoonCharacter *)relCharacter{
    if (!_relCharacter) {
        _relCharacter = [self userCharacter:USCartoonCharacterType_Rel];
    }
    return _relCharacter;
}

///用户设置的卡通角色
///
- (USCartoonCharacter *)userCharacter:(USCartoonCharacterType)type {
    
    UserPartsModel *mySetParts = [UserPartsModel mj_objectWithKeyValues:self.parts];
    UserPartsModel *relSetRelParts = [UserPartsModel mj_objectWithKeyValues:self.relUser.parts];

    if (type == USCartoonCharacterType_My) {

        if (!mySetParts && !relSetRelParts) {
            return (self.sex == USSexTypeFemale) ? [USCartoonCharacter defaultGirlCharacter] : [USCartoonCharacter defaultBoyCharacter];
        } else {
            NSArray *parts = (mySetParts.timestamp > relSetRelParts.timestamp) ? mySetParts.parts : relSetRelParts.relParts;
            USCartoonCharacter *model = [USCartoonCharacter new];
            model.parts = parts;
            return model;
        }
    } else {
        if (self.relStatus == 0) {
            if (!mySetParts) {
                return (self.sex == USSexTypeMale) ? [USCartoonCharacter defaultGirlCharacter] : [USCartoonCharacter defaultBoyCharacter];
            }
            USCartoonCharacter *model = [USCartoonCharacter new];
            model.parts = mySetParts.relParts;
            return model;
        }
        if (!mySetParts && !relSetRelParts) {
            return (self.relUser.sex == USSexTypeFemale) ? [USCartoonCharacter defaultGirlCharacter] : [USCartoonCharacter defaultBoyCharacter];
        } else {
            NSArray *parts = (mySetParts.timestamp > relSetRelParts.timestamp) ? mySetParts.relParts : relSetRelParts.parts;
            USCartoonCharacter *model = [USCartoonCharacter new];
            model.parts = parts;
            return model;
        }
    }
}



@end
